package fr.enssat.tpcloud.service;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import fr.enssat.tpcloud.dao.NotifDao;
import fr.enssat.tpcloud.dao.PostDao;
import fr.enssat.tpcloud.dao.UserDao;
import fr.enssat.tpcloud.model.Notif;
import fr.enssat.tpcloud.model.Post;
import fr.enssat.tpcloud.resource.NotifContainer;
import fr.enssat.tpcloud.resource.NotifData;
import fr.enssat.tpcloud.resource.PostContainer;
import fr.enssat.tpcloud.resource.PostData;

@Path("/notif")
public class NotifManagerService {
	
	private UserDao userDao;
	
	private PostDao postDao;
	
	private NotifDao notifDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public PostDao getPostDao() {
		return postDao;
	}

	public void setPostDao(PostDao postDao) {
		this.postDao = postDao;
	}

	public NotifDao getNotifDao() {
		return notifDao;
	}

	public void setNotifDao(NotifDao notifDao) {
		this.notifDao = notifDao;
	}
	
	@POST
	@Path("/addNotif")
	public Response postAddNotif(@FormParam("ident") int ident) throws URISyntaxException {
		
		
		System.out.println("postAddNotif::ident = " + ident);
		Post aPost = postDao.findPostById(ident);
		
		System.out.println("postAddNotif::identifiant du post = " + aPost.getId());
		
		// if new user : create it
        if (aPost != null) {
        	Notif newNotif = new Notif();
        	newNotif.setPost(aPost);
        	notifDao.save(newNotif);
        }
            
        return Response.noContent().build();	
	}
	

	
    @GET
    @Produces("application/json")
    public PostContainer getJsonMessage() {
        PostContainer result = new PostContainer();

        Collection<Notif> allNotif = notifDao.getAllNotif();
        
        List<PostData> saveData = new ArrayList<PostData>();

        for(Notif aNotif : allNotif) {
        	
            PostData data = new PostData();
            Post aPost = aNotif.getPost();
            data.setContent(aPost.getMessage());
            data.setEmail(aPost.getUser().getEmail());
            data.setRealName(aPost.getUser().getName());
            data.setId(aPost.getId());
            System.out.println("Notif numero "+aNotif.getId()+" Signale le post numero "+data.getId());
            long delay = (new Date()).getTime() - aPost.getCreationDate().getTime();
            data.setSince((delay/1000)+"s");
            saveData.add(data);
        }

        result.setAllPost(saveData);

        return result;
    }


}
